﻿namespace Pibby.Core.IO
{
	using System;
	using invrt;

	public static class VolumeFinder
	{
		public static bool IsVolumeConnected(string volumeName)
		{
			return VolumeFinder.FindVolume(volumeName) != null;
		}

		public static IDrive FindVolume(string volumeName)
		{
			IDriveFactory factory = InversionOfController.Factory.CreateTypeOf<IDriveFactory>();

			return FindVolume(volumeName, factory);
		}

		public static IDrive FindVolume(string volumeName, IDriveFactory factory)
		{
			if (string.IsNullOrEmpty(volumeName))
			{
				return null;
			}

			if (factory == null)
			{
				throw new ArgumentNullException("factory", "DriveFactory cannot be null");
			}

			IDriveCollection driveList = factory.GetAllDrives();

			foreach (IDrive drive in driveList)
			{
				try
				{
					if (drive.IsReady && drive.VolumeLabel.Equals(volumeName, StringComparison.CurrentCultureIgnoreCase))
					{
						return drive;
					}
				}
				catch (System.IO.IOException)
				{
					// may be trying to connect to drives that are not ready - swallow this exception
				}
			}

			return null;
		}
	}
}
